import Vue from 'vue'
import axios from 'axios'

// axios 全局配置
axios.defaults.timeout = 30000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.baseURL = '/static/data'

//请求拦截器
axios.interceptors.request.use((config) => {
    //在发送请求之前做某事
    return config
}, (err) => {
    return Promise.reject(err)
})

//响应拦截器
axios.interceptors.response.use((response) => {
    //对响应数据做些事
    return response
}, (err) => {
    return Promise.reject(err)
})

export function $http(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, params).then(response => {
            resolve(response)
        }).catch(function(err) {
            if (err.response) {
                switch (err.response.status) {
                    case 404:
                        Vue.$Toast('所请求的页面不存在或已被删除!')
                        break
                    default:
                        Vue.$Toast('服务器未响应，请重试!')
                }
            } else {
                Vue.$Toast('网络异常，请重试!')
                return false
            }
        })
    })
}

//API
export default {
    get_home_data() {
        return $http('/home.json')
    },
    get_product_list(params) {
        return $http('/list.json', params)
    },
    get_classify_index(params) {
        return $http('/classifyIndex.json', params)
    },
    get_today_index(params) {
        return $http('/today_index.json', params)
    },
    get_integral_index(params) {
        return $http('/integral_index.json', params)
    },
    get_search_list(params) {
        return $http('/getkeys.json', params)
    },
    get_product_detail(params) {
        return $http('/detail.json', params)
    },
    get_cart_list(params) {
        return $http('/cart.json', params)
    }
}